<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '确认订单',
    navigationBarRightButton: {
      hide: true,
    },
  },
}
</route>
<template>
  <!-- page-meta 只能是页面内的第一个节点 -->
  <page-meta :page-style="`overflow:${popupShow ? 'hidden' : 'visible'};`"></page-meta>
  <view
    class="w-full h-full bg-white overflow-hidden box-border"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="w-full h-full pos-relative z-1 bg-#F6F6F8">
      <wd-navbar @click-left="handleClickLeft">
        <template #title>
          <text class="text-gray-333 font-size-36 font-500">确认订单</text>
        </template>
        <template #left>
          <wd-icon name="chevron-left" class="text-gray-333 font-size-44"></wd-icon>
        </template>
      </wd-navbar>
      <view class="w-full h-full home-content ps-b-180">
        <view
          class="p-x-28 p-y-34 flex justify-between items-center bg-white"
          @click="chooseAddress"
        >
          <view class="font-size-32 font-400 text-gray-333" v-if="!orderInfo.addressItem">
            请选择收货地址
          </view>
          <view v-else>
            <view class="font-size-32 font-500 text-gray-333">
              {{
                orderInfo.addressItem?.province +
                ' ' +
                orderInfo.addressItem?.city +
                ' ' +
                orderInfo.addressItem?.district +
                ' ' +
                orderInfo.addressItem?.address
              }}
            </view>
            <view class="font-size-28 font-400 text-gray-333 mg-t-20">
              {{ orderInfo.addressItem?.name + ' ' + orderInfo.addressItem?.mobile }}
            </view>
          </view>
          <wd-icon name="chevron-right" class="font-size-44 text-gray-999"></wd-icon>
        </view>
        <view
          class="flex justify-start items-center p-x-28 p-y-34 bg-white mg-t-20"
          v-for="(item, index) in productList"
          :key="index"
        >
          <view class="wr-160 hr-160 b-rd-8 overflow-hidden">
            <image width="100%" height="100%" :src="item.pic" mode="scaleToFill" />
          </view>
          <view class="wr-500 mg-l-24">
            <view
              class="flex justify-between items-start font-size-28 font-500 text-gray-333 line-h-40"
            >
              <view>{{ item.name }}</view>
              <view class="mg-l-50">￥{{ item.price }}</view>
            </view>
            <view
              class="flex justify-between items-start font-size-24 font-400 text-gray-999 line-h-36 mg-t-24"
            >
              <view>{{ item.title }}</view>
              <view>X{{ item.count }}</view>
            </view>
          </view>
        </view>
        <view class="p-x-28 p-y-34 flex justify-between items-center bg-white mg-t-20">
          <view class="font-size-32 font-400 text-gray-333">商品数量</view>
          <view class="font-size-32 font-500 text-gray-333">
            <text>{{ orderInfo.orderCount }}</text>
          </view>
        </view>
        <view class="p-x-28 p-y-34 flex justify-between items-center bg-white mg-t-20">
          <view class="font-size-32 font-400 text-gray-333">商品金额</view>
          <view class="font-size-32 font-500 text-gray-333">
            <text>￥{{ orderInfo.orderPrice }}</text>
          </view>
        </view>
        <view
          class="p-x-28 p-y-34 flex justify-between items-center bg-white"
          @click="chooseCoupons"
        >
          <view class="font-size-32 font-400 text-gray-333">优惠券</view>
          <view class="flex justify-center items-center">
            <text class="font-size-32 font-500 text-blue-1">
              {{ orderInfo.orderCoupons ? orderInfo.orderCoupons?.title : '未使用优惠卷' }}
            </text>
            <wd-icon name="chevron-right" class="font-size-44 text-gray-999"></wd-icon>
          </view>
        </view>
        <view class="p-x-28 p-y-34 flex justify-between items-center bg-white">
          <view class="font-size-32 font-400 text-gray-333">天琴币抵扣</view>
          <view class="flex justify-center items-center">
            <text class="font-size-32 font-500 text-blue-1">￥{{ orderInfo.boundsPay }}</text>
          </view>
        </view>
        <view class="p-x-28 p-y-34 flex justify-between items-center bg-white">
          <view class="font-size-32 font-400 text-gray-333">运费</view>
          <view class="font-size-32 font-500 text-gray-333">
            <text>￥{{ orderInfo.expressFee }}</text>
          </view>
        </view>
        <view class="mg-t-20 p-x-28 p-y-32 bg-white">
          <view class="font-size-32 font-500 text-gray-333">支付方式</view>
          <!-- <view class="flex justify-between items-center mg-t-32">
            <view class="flex justify-start items-center">
              <view class="wr-50 hr-44 bg-cover bg-center bg-no-repeat">
                <image
                  width="100%"
                  height="100%"
                  src="../../static/images/icons/icon-tqb.png"
                  mode="scaleToFill"
                />
              </view>
              <view class="font-size-32 font-400 text-gray-333 mg-l-30">天琴币</view>
            </view>
            <view>
              <wd-checkbox
                v-model="checkedGroup.check0"
                @change="handleChange('check0', 0)"
              ></wd-checkbox>
            </view>
          </view> -->
          <view class="flex justify-between items-center mg-t-32">
            <view class="flex justify-start items-center">
              <view class="wr-50 hr-50">
                <image
                  width="100%"
                  height="100%"
                  src="../../static/images/icons/icon-wx.png"
                  mode="scaleToFill"
                />
              </view>
              <view class="font-size-32 font-400 text-gray-333 mg-l-30">微信</view>
            </view>
            <view>
              <wd-checkbox
                v-model="checkedGroup.check1"
                @change="handleChange('check1', 1)"
              ></wd-checkbox>
            </view>
          </view>
          <!-- <view class="flex justify-between items-center mg-t-32">
            <view class="flex justify-start items-center">
              <view class="wr-46 hr-46">
                <image
                  width="100%"
                  height="100%"
                  src="../../static/images/icons/icon-zfb.png"
                  mode="scaleToFill"
                />
              </view>
              <view class="font-size-32 font-400 text-gray-333 mg-l-30">支付宝</view>
            </view>
            <view>
              <wd-checkbox
                v-model="checkedGroup.check2"
                @change="handleChange('check2', 2)"
              ></wd-checkbox>
            </view>
          </view>
          <view class="flex justify-between items-center mg-t-32">
            <view class="flex justify-start items-center">
              <view
                class="wr-54 hr-28 bg-cover bg-center bg-no-repeat"
                :style="{ backgroundImage: 'url(../../static/images/icons/icon-ylzf.png)' }"
              ></view>
              <view class="font-size-32 font-400 text-gray-333 mg-l-30">中国银联</view>
            </view>
            <view>
              <wd-checkbox
                v-model="checkedGroup.check3"
                @change="handleChange('check3', 3)"
              ></wd-checkbox>
            </view>
          </view> -->
        </view>
        <view class="mg-t-20 p-x-28 p-y-32 bg-white">
          <view class="font-size-32 font-500 text-gray-333">备注</view>
          <view class="w-full b-solid-#F2F2F2-2 b-rd-16 mg-t-28 overflow-hidden">
            <wd-textarea
              custom-textarea-class="hr-156 font-size-28 text-gray-999 font-400"
              v-model="OrderInfo.remark"
              placeholder="请输入商品备注"
            />
          </view>
        </view>
      </view>
      <view
        class="pos-absolute pos-bottom-0 pos-left-0 w-full hr-156 bg-white flex justify-between items-center p-x-32"
      >
        <view class="flex justify-start items-end">
          <view class="font-size-28 font-400 text-gray-333">实付</view>
          <view class="flex justify-start items-end mg-l-12">
            <view class="font-size-26 font-500 text-gray-333">￥</view>
            <view class="font-size-32">{{ orderInfo.realPrice }}</view>
          </view>
        </view>
        <view class="wr-224 hr-80">
          <wd-button
            custom-class=" text-white font-size-32"
            type="primary"
            size="small"
            @click="buyProduct"
          >
            <text>立即购买</text>
          </wd-button>
        </view>
      </view>
    </view>
  </view>
  <wd-popup
    v-model="popupShow"
    lock-scroll
    position="bottom"
    :safe-area-inset-bottom="true"
    @close="closePopup"
  >
    <view class="w-full hr-948">
      <view class="w-full h-full p-x-28 p-y-32 border-box pos-relative">
        <view
          class="pos-absolute pos-top-28 pos-right-32 z-1 font-size-28 font-500 text-gray-999"
          @click="closePopup"
        >
          <wd-icon name="close"></wd-icon>
        </view>
        <view class="flex justify-center">
          <text class="font-size-32 font-500 text-gray-333">选择优惠券</text>
        </view>
        <view>
          <view
            class="w-full hr-236 pos-relative z-1 mg-t-32"
            v-for="(item, index) in couponList"
            :key="index"
          >
            <view class="pos-absolute pos-top-0 pos-left-0 w-full h-full z-0">
              <image
                width="100%"
                height="100%"
                :src="'../../static/images/background/coupon-bg.png'"
              />
            </view>
            <view class="pos-relative z-1 p-x-28 p-y-28">
              <view class="flex justify-between items-center">
                <view class="flex justify-start items-end text-blue-1 font-600 line-height-none">
                  <view class="font-size-28 mg-b-6 mg-r-6">¥</view>
                  <view class="font-size-64">{{ item.amount }}</view>
                </view>
                <view class="hr-70 flex justify-end items-end">
                  <wd-checkbox
                    v-model="item.checked"
                    @change="couponChange(item.checked, item.id)"
                  ></wd-checkbox>
                </view>
              </view>
              <view class="mg-t-6 p-x-5">
                <text class="font-size-28 text-gray-333 font-500">{{ item.type }}</text>
              </view>
              <view class="mg-t-26">
                <text class="font-size-24 text-gray-999 font-400" v-if="item.expire_at">
                  使用期限：{{ item.expire_at }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </wd-popup>
</template>

<script lang="ts" setup>
import { usePayTool } from '@/hooks/usePayTool'
import { addAddress, getAddressList, getMyCoupons } from '@/service/my/my'
import { createOrder, getOrderConfirm, orderPay } from '@/service/shop/shop'
import { useUserStore } from '@/store'

defineOptions({
  name: 'ConfirmOrder',
})
const checkedGroup = ref({
  check0: false,
  check1: true,
  check2: false,
  check3: false,
})
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const handleClickLeft = () => {
  uni.navigateBack()
}
onLoad(() => {})
onShow(() => {
  getOrder()
})
// const getData = () => {
//   const data: any = {
//     status: 0,
//   }
//   getMyCoupons(data).then((res: any) => {
//     const data: any = res.data
//     if (data) {
//       data.data.map((m: any) => {
//         if (m.id === OrderInfo.value.couponId) {
//           m.checked = true
//         } else {
//           m.checked = false
//         }
//       })
//       couponList.value = data.data
//       popupShow.value = true
//     }
//   })
// }
const couponList: any = ref([])
const couponChange = (ev: any, id: any) => {
  let priceCount: any = 0
  couponList.value.map((m: any) => {
    if (ev) {
      if (m.id === id) {
        m.checked = ev
        orderInfo.value.orderCoupons = m
        OrderInfo.value.couponId = id
        priceCount += m.amount
      } else {
        m.checked = false
      }
    } else {
      if (m.id === OrderInfo.value.couponId) {
        priceCount -= m.amount
        orderInfo.value.orderCoupons = null
        OrderInfo.value.couponId = ''
      }
      m.checked = false
    }
    return m
  })
  orderInfo.value.realPrice = (orderInfo.value.realPrice * 100 - priceCount * 100) / 100
}
const orderInfo: any = ref({
  orderCount: 0,
  orderPrice: 0,
  orderCoupons: null,
  couponDeduct: 0,
  boundsPay: 0,
  realPrice: 0,
  addressItem: null,
  expressFee: 0,
})
const productList = ref([])
const getOrder = () => {
  const userStore = useUserStore()
  if (userStore.userInfo) {
    createParam.shareUserId = (userStore.userInfo as any).user.id
  }
  const pro: any = uni.getStorageSync('buyProduct')
  if (pro) {
    const proData: any = JSON.parse(pro)
    const param: any = {
      skuIds: String(proData.id),
      skuNums: String(proData.num),
    }
    createParam.skuIds = String(proData.id)
    createParam.skuNums = String(proData.num)
    getOrderConfirm(param).then((res: any) => {
      if (res.data) {
        let skuIdCount: any = 0
        let skuNumCount: any = 0
        let expressFee: any = 0
        res.data.data.map((m: any) => {
          m.count = String(proData.num).split(',')[
            String(proData.id).split(',').indexOf(String(m.id))
          ]
          skuIdCount += Number(m.count)
          skuNumCount += (m.price * 100 * m.count) / 100
          expressFee += Number(m.express_fee.split(',')[1])
          return m
        })
        orderInfo.value.expressFee = expressFee
        orderInfo.value.orderCount = skuIdCount
        orderInfo.value.orderPrice = skuNumCount
        productList.value = res.data.data
        const coupons = res.data.coupons
        OrderInfo.value.couponId = res.data.couponSel
        couponList.value = coupons
        couponList.value.map((m: any) => {
          if (m.id === OrderInfo.value.couponId) {
            m.checked = true
          } else {
            m.checked = false
          }
          return m
        })
        if (coupons && coupons.length > 0) {
          const firstCoupon = coupons.filter((f: any) => {
            return f.id === res.data.couponSel
          })
          if (firstCoupon && firstCoupon.length > 0) {
            orderInfo.value.orderCoupons = firstCoupon[0]
            // 创建订单信息
            createParam.userCouponId = firstCoupon[0].id
          }
        }
        orderInfo.value.couponDeduct = res.data.couponDeduct
        orderInfo.value.realPrice = res.data.realPrice
        // 创建订单信息
        createParam.deduct = res.data.deduct
        createParam.amount = res.data.realPrice
      }
    })
  }
  const address = uni.getStorageSync('chooseAddress')
  let addressId: any = null
  if (address) {
    const obj: any = JSON.parse(address)
    if (obj.addressId) {
      addressId = obj.addressId
      uni.setStorageSync('chooseAddress', null)
    }
  }
  getAddressList().then((res: any) => {
    if (res.data) {
      let firstAddress: any = []
      if (addressId) {
        firstAddress = res.data.filter((f: any) => {
          return f.id === addressId
        })
      } else {
        firstAddress = res.data.filter((f: any) => {
          return f.is_default === 1
        })
      }
      if (firstAddress && firstAddress.length > 0) {
        orderInfo.value.addressItem = firstAddress[0]
      }
    }
  })
}
const handleChange = (e: any, value: any) => {
  for (const i in checkedGroup.value) {
    checkedGroup.value[i] = false
  }
  checkedGroup.value[e] = true
  createParam.payType = value
}
const chooseAddress = () => {
  uni.setStorageSync(
    'chooseAddress',
    JSON.stringify({ chooseAddress: true, addressId: orderInfo.value.addressItem.id }),
  )
  uni.navigateTo({
    url: '/pages/location/listLocation',
  })
}
const OrderInfo: any = ref({
  couponId: '',
  remark: '',
})
const popupShow = ref(false)
const closePopup = () => {
  popupShow.value = false
}
const chooseCoupons = () => {
  // getData()
  popupShow.value = true
}
const createParam = {
  skuIds: '', // 商品sku ID 必填
  skuNums: '', // 商品sku 数量 必填
  shareUserId: '',
  orderId: '', // 订单ID 再次支付必填
  payType: 1, // 支付方式:0=天琴币,1=微信,2=支付宝,3=银联  必填
  deduct: '', // 抵扣 必填(天琴币非必填，再次支付非必填)
  userCouponId: '', // 优惠券ID 必填(天琴币非必填，再次支付非必填)
  amount: 0, // 订单实际支付金额 必填(天琴币非必填，再次支付非必填)
  remark: '', // 备注 必填(再次支付非必填)
  expressFee: 0, // 快递费 必填(再次支付非必填)
}
const payTools = usePayTool()
const buyProduct = () => {
  createParam.remark = OrderInfo.value.remark
  createParam.userCouponId = OrderInfo.value.couponId
  createParam.amount = (orderInfo.value.orderPrice * 100 - orderInfo.value.couponDeduct * 100) / 100
  if (createParam.amount <= 0) {
    createOrder(createParam).then((res: any) => {
      if (res.data) {
        const item: any = {
          name: '待付款',
        }
        if (res.errMsg === 'requestPayment:ok') {
          item.name = ''
        } else {
          item.name = '待付款'
        }
        uni.setStorageSync('orderStatus', JSON.stringify(item))
        uni.navigateTo({
          url: '/pages/shopping/allOrder',
        })
      }
    })
  } else {
    createOrder(createParam).then((res: any) => {
      if (res.data) {
        const id: any = res.data.id
        orderPay({ id }).then((res: any) => {
          // 支付
          payTools.payTool(res.data)
        })
      }
    })
  }
}
</script>

<style scoped lang="scss">
.home-content {
  height: calc(100% - var(--wot-navbar-height, 88rpx));
  overflow: auto;
}
::v-deep .wd-search {
  padding: 0 !important;
  background: rgba(255, 255, 255, 0) !important;
}
::v-deep .wd-button {
  width: 100% !important;
  height: 100% !important;
}
</style>
